package com.rover.controller.system;

import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.common.SessionContext;
import com.common.SessionInfo;
import com.common.Common;
import com.grid.Page;
import com.rover.entity.system.User;
import com.rover.service.system.SysParamService;
import com.rover.service.system.UserLogService;
import com.rover.service.system.UserRoleService;
import com.rover.service.system.UserService;
import com.utils.AppUtil;
import com.utils.Encrypt;

/**
 * 用户
 */
@Controller
@RequestMapping("/userController")
public class UserController {

	@Autowired
	private UserService userService;

	@Autowired
	private SysParamService sysParamService;
	
	@Autowired
	private UserLogService userLogService;
	
	@Autowired
	private UserRoleService userRoleService;

	// 用户登录
	@RequestMapping(value = { "/login" })
	public @ResponseBody
	Map<String, Object> login(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String userName = request.getParameter("name");
		String password = request.getParameter("pwd");
		String clientIp = request.getRemoteAddr();
		Map<String, Object> map = new HashMap<String, Object>();
		String msg = null;
		if (StringUtils.isNotBlank(userName)) {
			User user = userService.getUserByUserName(userName);
			if (user != null) {
				String originalPwd = user.getPassword();
				password = Encrypt.md5(password);
				if (originalPwd.equals(password)) {
					int status = user.getStatus();
					if (status == Common.ENABLE_STATUS) {// 启用
						// 登陆成功
						SessionInfo sessionInfo = new SessionInfo();
						sessionInfo.setUser(user);
						sessionInfo.setLoginTime(new Date());
						sessionInfo.setClientIp(clientIp);
						sessionInfo.setIsAdmin(userService.getIsAdmin(user));
						HttpSession session = request.getSession(true);
						session.setAttribute("sessionInfo", sessionInfo);
						
						//记录登陆日志
						userLogService.log(request, user,userName+"登录");

						//判断系统参数是否能重复登录
						String strVal = sysParamService
								.getCodeValue("user_RepeatLogin");
						// 获取session管理器
						SessionContext sc = SessionContext.getInstance();
						if (strVal.equals("N")) {
							sc.setRepeatLogin(false);
							// 判断是否存在此用户
							if (sc.getAllSession().containsKey(user.getId())) {
								// 消除session
								sc.DelSession(user.getId());
							}
							sc.AddSession(user.getId(), session);
						}
						else{
							sc.AddSession(session.getId(), session);
						}
						map.put("success", Boolean.TRUE);
					} else {
						// 未启用
						map.put("success", Boolean.FALSE);
						msg = "该用户未启用";
					}
				} else {
					// 密码不正确
					map.put("success", Boolean.FALSE);
					msg = "密码不正确";
				}
			} else {
				// 用户不存在
				map.put("success", Boolean.FALSE);
				msg = "用户不存在";
			}
		}
		map.put("message", msg);
		return map;
	}

	// 用户管理
	@RequestMapping("/query")
	@ResponseBody
	public Map<String, Object> query(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String loginName = (String) request.getParameter("loginName");
		String hql = "";
		if (null != loginName) {
			hql = "where loginName like '%" + loginName + "%'";
		}
		Map<String, Object> params = new HashMap<String, Object>();
		Page<User> page = new Page<User>(request);
		page = userService.query(page, params, hql);
		map = AppUtil.buildJSONDataResponse(page.getResult(),
				page.getTotalCount());
		return map;
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> save(User user, HttpServletRequest request)
			throws Exception {
		// UserSession u = (UserSession)
		// request.getSession().getAttribute("userSession");
		Map<String, Object> map = new HashMap<String, Object>();
		Boolean success = true;
		String message = "";
		
		try {
			if (null == user.getId()) {
				success = userService.isAddNameRepeat(user.getLoginName());
			} else {
				success = userService.isEditNameRepeat(user.getLoginName(),
						user.getId());
			}
			// 判断是否验证成功
			if (success) {
				userService.save(user);
			} else {
				message = "此用戶名称已存在，请重新输入！";
			}
			map.put("success", success);
			map.put("message", message);
		} catch (Exception e) {
			// logger.error(e.getMessage(), e);
			map.put("success", false);
			map.put("message", e.getMessage());
		}
		return map;
	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> delete(@RequestParam("id") String id, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		// String id = request.getParameter("id");
		try {
			//获取用户
			User u = userService.getUserById(id);
			//删除用户角色
			userRoleService.deleteRoles(u);
			//删除用户日志
			userLogService.deleteLogs(u);
			//刪除
			userService.delete(Long.parseLong(id));
			map.put("success", true);
			map.put("message", "");
		} catch (Exception e) {
			map.put("success", false);
			map.put("message", e.getMessage());
		}
		return map;
	}

	@RequestMapping(value = "/initPassword", method = RequestMethod.POST)
	@ResponseBody
	public void initPassword(@RequestParam("ids") String ids) {
		String[] userIds = ids.split(",");
		for (String id : userIds) {
			userService.initPassword(Long.valueOf(id));
		}
	}

	// 密码修改
	@RequestMapping(value = "/savePwd", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> savePassword(HttpServletRequest request) {
		HttpSession session = request.getSession();
		SessionInfo info = (SessionInfo) session.getAttribute("sessionInfo");
		User user = info.getUser();
		String password = request.getParameter("password");
		String newPwd = request.getParameter("newPwd");
		String newPwdTwo = request.getParameter("newPwdTwo");
		return userService.savePassword(user.getId(), password, newPwd,
				newPwdTwo);
	}

	// 注销
	@RequestMapping("/logout")
	public void logout(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		HttpSession session = request.getSession();
		try{
			SessionInfo info = (SessionInfo) session.getAttribute("sessionInfo");
			//记录注销日志
			User user = info.getUser();
			userLogService.log(request, user, "退出程序");
			
			// 获取session管理器
			SessionContext sc = SessionContext.getInstance();
			// 判断是否存在此用户
			if (sc.getAllSession().containsKey(user.getId())) {
				// 消除session
				sc.DelSession(info.getUser().getId());
			} else {
				session.invalidate();
			}
			map.put("success", Boolean.TRUE);
		}catch(Exception e){
			map.put("success", Boolean.FALSE);
			map.put("message", "注销失败");
		}
		
		buildCustomJSONDataResponse(response, map);
	}

	public static void buildCustomJSONDataResponse(
			HttpServletResponse response, Map<String, ? extends Object> data)
			throws Exception {
		JSONObject jsonObject = JSONObject.fromObject(data);
		response.setContentType(Common.JSON_TYPE + ";charset="
				+ Common.DEFAULT_ENCODING);
		response.setDateHeader("Expires", 0);
		response.addHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.write(jsonObject.toString());
	}

	// 启用禁用
	@RequestMapping("/enable")
	@ResponseBody
	public Map<String, Object> enable(@RequestParam("ids") String ids) {
		Map<String, Object> map = new HashMap<String, Object>();
		Boolean flag = Boolean.TRUE;
		map.put("success", flag);
		String[] idList = ids.split(",");
		for (String id : idList) {
			if (StringUtils.isBlank(id)) {
				continue;
			}
			User user = userService.getUserById(id);
			if (null != user) {
				int status = user.getStatus();
				if (status == 1) {
					user.setStatus(Common.FORBIDDEN_STATUS);
				} else {
					user.setStatus(Common.ENABLE_STATUS);
				}
				userService.saveEnable(user);
			}
		}
		return map;
	}

	// 重定向登陆页面
	@RequestMapping("/index")
	public String index() {
		return "redirect:login.jsp";
	}
}
